﻿using System.Drawing;
using System.Windows;
using ChatClient.Models;
using ChatClient.Services;
using ChatClient.Tools;
using DotnetUtil.Extensions;
using DotnetUtil.Services;
using Prism.Commands;
using Prism.Mvvm;

namespace ChatClient.ViewModels
{
    internal class LoginWindowViewModel : BindableBase
    {
        public event Action CloseWindow = () => { };
        public event Action LoginSuccess = () => { };

        #region 依赖属性

        public DelegateCommand CloseWindowCommand { get; set; }
        public DelegateCommand SelectProfilePicCommand { get; set; }
        public DelegateCommand LoginCommand { get; set; }

        public string? ProfilePic
        {
            get => _profilePic;
            set => SetProperty(ref _profilePic, value);
        }

        public string? UserName
        {
            get => _userName;
            set => SetProperty(ref _userName, value);
        }

        public bool LoginButtonEnable
        {
            get => _loginButtonEnable;
            set => SetProperty(ref _loginButtonEnable, value);
        }

        public Visibility LoadingVisibility
        {
            get => _loadingVisibility;
            set => SetProperty(ref _loadingVisibility, value);
        }

        private string? _profilePic;
        private string? _userName;
        private bool _loginButtonEnable = true;
        private Visibility _loadingVisibility = Visibility.Collapsed;

        #endregion

        private readonly ILogService _logService;
        private readonly IChatService _chatService;
        private readonly IDialogService _dialogService;
        private readonly ISessionService _sessionService;

        public LoginWindowViewModel(
            ILogService logService,
            IChatService chatService,
            IDialogService dialogService,
            ISessionService sessionService
        )
        {
            _logService = logService;
            _chatService = chatService;
            _dialogService = dialogService;
            _sessionService = sessionService;

            CloseWindowCommand = new DelegateCommand(OnCloseWindow);
            SelectProfilePicCommand = new DelegateCommand(OnSelectProfilePic);
            LoginCommand = new DelegateCommand(OnLoginAsync);
        }

        private void OnCloseWindow()
        {
            CloseWindow.Invoke();
        }

        private void OnSelectProfilePic()
        {
            var pic = _dialogService.OpenFile("Select image file", "Images (*.jpg;*.png)|*.jpg;*.png");
            if (!string.IsNullOrEmpty(pic))
            {
                var img = Image.FromFile(pic);
                if (img.Width > Constants.MaxImageWidth || img.Height > Constants.MaxImageHeight)
                {
                    _dialogService.ShowNotification(
                        $"图片尺寸不大于 {Constants.MaxImageWidth} x {Constants.MaxImageHeight}");
                    return;
                }

                ProfilePic = pic;
            }
        }

        private async void OnLoginAsync()
        {
            if (!_sessionService.IsConnected)
            {
                _dialogService.ShowNotification("服务器未连接", "提示");
                return;
            }

            if (string.IsNullOrWhiteSpace(UserName))
            {
                _dialogService.ShowNotification("请输入用户名", "提示");
                return;
            }

            LoginButtonEnable = false;
            LoadingVisibility = Visibility.Visible;

            _sessionService.ProfilePic = ProfilePic;
            _sessionService.UserName = UserName;

            try
            {
                var avatar = _sessionService.GetAvatar();
                var ret = await _chatService.LoginAsync(UserName, avatar);
                if (!ret.Item1)
                {
                    _dialogService.ShowNotification("用户名被占用");
                    return;
                }

                var userList = ret.Item2;
                userList.ForEach(u =>
                    _sessionService.Participants.Add(new Participant { Name = u.Name, Photo = u.Photo }));
                _sessionService.IsLoggedIn = true;

                LoginSuccess.Invoke();
            }
            catch (Exception e)
            {
                _logService.Error($"登录失败：{e.GetFullMessage()}");
                _dialogService.ShowNotification(e.GetFullMessage(), "登录失败");
            }
            finally
            {
                LoginButtonEnable = true;
                LoadingVisibility = Visibility.Collapsed;
            }
        }
    }
}
